package com.briup.demo.web.controller;

import com.briup.demo.bean.UserFile;
import com.briup.demo.service.UserFileService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author wyq
 * @create 2021-11-14 17:50
 */
@Controller
public class UserFileController {
    @Autowired
    private UserFileService userFileService;

    /**
     * Description: TODO  上传文件
     *
     * @author: wyq
     * @date: 2021/11/14 17:51
     * @Param userFile:
     * @return: java.lang.String
     */
    @PostMapping("/upload")
    public String upload(@RequestPart("file") MultipartFile file, HttpSession session) throws IOException {
        //解决空提交的问题
        if (file.isEmpty()) {
            return "index";
        }
        //获取文件的原始名称
        String oldFilename = file.getOriginalFilename();
        //获取文件后缀
        String extension = "." + FilenameUtils.getExtension(oldFilename);
        //通过UUID生成新的文件名称
        String newFileName = UUID.randomUUID().toString().replace("-", "") + extension;
        // 将新的文件名保存在model中
        session.setAttribute("newFileName", newFileName);
        //文件大小
        long fileSize = file.getSize();
        // 文件类型
        String type = file.getContentType();
        // 处理根据日期生成目录
        // 文件存放的基础路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files/";
        // 构建按照日期存放的文件夹
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = realPath + format;
        // 文件目录
        File dateDir = new File(dateDirPath);
        // 创建目录
        if (!dateDir.exists()) dateDir.mkdirs();
        // 处理文件上传
        file.transferTo(new File(dateDirPath, newFileName));
        // 将文件信息放入数据库中
        UserFile userFile = new UserFile(null, oldFilename, newFileName, fileSize + "", type, "/files/" + format, new Date());
        userFileService.save(userFile);
        //回到首页
        return "redirect:/index";
    }

    /**
     * Description: TODO  返回首页，解决无法获取session中数据的bug
     *
     * @author: wyq
     * @date: 2021/11/14 20:23
     * @return: java.lang.String
     */

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * Description: TODO  文件下载
     *
     * @author: wyq
     * @date: 2021/11/14 17:54
     * @Param name:
     * @return: java.lang.String
     */

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response, HttpSession session) {
        try {
            //查询到对应的文件信息
            UserFile byName = userFileService.findByName(name);
            //根据文件信息中的文件名，文件存储路径获取文件输入流
            String fileRealPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + byName.getPath();
            // 获取文件输入流
            FileInputStream fis = new FileInputStream(new File(fileRealPath, byName.getNewFileName()));
            // 附件下载
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(byName.getOldFileName(), "UTF-8"));
            // 获取响应输出流
            ServletOutputStream os = response.getOutputStream();
            // 文件拷贝
            IOUtils.copy(fis, os);
            //关闭流
            IOUtils.closeQuietly(os);
            IOUtils.closeQuietly(fis);
            session.setAttribute("code", "200");
        } catch (IOException e) {
            session.setAttribute("code", "410");
            e.printStackTrace();
        }
    }

    /**
     * Description: TODO  获取文件信息以json格式返回
     *
     * @author: wyq
     * @date: 2021/11/14 17:56
     * @Param name:
     * @return: java.lang.String
     */

    @GetMapping("/find")
    @ResponseBody
    public Object getFileMessage(String name) {
        return userFileService.findByName(name);
    }
}
